package com.twang.stock.task;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.task.old.BaseTask;
import com.twang.stock.utils.date.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 *
 */
@Slf4j
@Service
public class PhoneCallTask extends BaseTask {

    @Autowired
    private CommonService commonService;

//    @Scheduled(cron = "0 0/1 * * * ?")
    public void excute() {
        if (DateUtils.JudgeTime("09:30:00", "18:00:00")) {
            String result = getRequest();
            try {
                Response response = JSONObject.parseObject(result, Response.class);
                if (null != response) {
                    List<Data> listData = response.getData();
                    if (CollectionUtils.isNotEmpty(listData)) {
                        int times = Integer.parseInt(listData.get(0).getTime());
                        if (times < 1) {
                            postRequest();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.info(">>>>>> 非工作时间，不轰炸！");
        }
    }

    public static void main(String[] args) {


    }

    public  void postRequest() {
        try {
            // URL 设置
            URL url = new URL("https://fczdx.fcz6.xyz/user/ajax/order/act/add");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");

            // 添加请求头（包括 Cookie 和 Content-Type）
            String cookies =commonService.getValue("PHONE_CALL_COOKIE").toString();
            connection.setRequestProperty("Cookie", cookies);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 允许写入数据到请求体
            connection.setDoOutput(true);

            // 准备表单数据
            String urlParameters = commonService.getValue("PHONE_CALL").toString();;

            // 写入数据到请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("POST Response Code :: " + responseCode);
            StringBuilder response = new StringBuilder();
            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) { // 响应码 200 表示成功
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), StandardCharsets.UTF_8));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印结果
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("POST request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  String getRequest() {
        try {
            // 准备参数
            String params = "page=1&limit=15";

            // URL 设置，包含参数
            URL url = new URL("https://fczdx.fcz6.xyz/user/ajax/order/act/list?" + params);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 GET
            connection.setRequestMethod("GET");

            // 添加请求头（包括 Cookie）
           // String cookies = "tvfe_boss_uuid=e4a74a278eca0811; qq_domain_video_guid_verify=b98376cb098acc7d; pgv_pvid=2442866680; PHPSESSID=c17b4389e9b7a046421e75e6b382a9d9; Let_IndexUsername=xxx199; Let_IndexPassword=d70d0e47d2da107eb7d79236483eb88a";
            String cookies =commonService.getValue("PHONE_CALL_COOKIE").toString();
            connection.setRequestProperty("Cookie", cookies);

            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("GET Response Code :: " + responseCode);

            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) { // 响应码 200 表示成功
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), StandardCharsets.UTF_8));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印结果
                System.out.println("Response: " + response.toString());
                return response.toString();
            } else {
                System.out.println("GET request not worked");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @lombok.Data
    public static class Response {
        private String code;
        private List<Data> data;
        private String msg;
        private int count;

        // getters and setters for all fields


    }
    @lombok.Data
    public static class Data {
        private int id;
        private String uid;
        private String phone;
        private String time;
        private int isdel;
        private String lasttime;
        private String endtime;
        private String addtime;

        // getters and setters for all fields
    }

}
